package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.RichTextStringData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONArray;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.utilities.PdfTable;
import com.spire.pdf.utilities.PdfTableExtractor;
import lombok.RequiredArgsConstructor;
import me.zhengjie.config.FileProperties;
import me.zhengjie.config.MappingProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Document;
import me.zhengjie.modules.system.domain.DocumentParagraph;
import me.zhengjie.modules.system.domain.DocumentTable;
import me.zhengjie.modules.system.repository.DocumentParagraphRepository;
import me.zhengjie.modules.system.repository.DocumentRepository;
import me.zhengjie.modules.system.repository.DocumentTableRepository;
import me.zhengjie.modules.system.service.DocumentService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.DocumentMapper;
import me.zhengjie.modules.system.service.mapstruct.DocumentParagraphMapper;
import me.zhengjie.modules.system.service.mapstruct.DocumentTableMapper;
import me.zhengjie.util.DocumentUtils;
import me.zhengjie.util.FileTypeEnum;
import me.zhengjie.util.ReadWord;
import me.zhengjie.util.ReadWordCopy;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.StringUtils;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * DocumentServiceImpl
 *
 * @author guoyuan
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "doc")
public class DocumentServiceImpl implements DocumentService {

    private static final String DOC_TYPE_UPLOAD = "0";
    private static final String DOC_TYPE_CUSTOM = "1";
    private static final String DOC_TYPE_MODEL = "2";
    private final DocumentRepository documentRepository;
    private final DocumentParagraphRepository documentParagraphRepository;
    private final DocumentTableRepository documentTableRepository;
    private final DocumentMapper documentMapper;
    private final DocumentParagraphMapper documentParagraphMapper;
    private final DocumentTableMapper documentTableMapper;
    private final FileProperties fileProperties;
    private final MappingProperties mappingProperties;
    @Value("${upload.filePath}")
    public String filePath;

    @Override
    public File upload(String name, Boolean isModel, MultipartFile multipartFile, String suffix) throws Exception {
        FileUtil.checkSize(fileProperties.getMaxSize(), multipartFile.getSize());
        if (StringUtils.isEmpty(name)) {
            throw new BadRequestException("文件名不能为空");
        }
        if (ObjectUtil.isNull(isModel)) {
            throw new BadRequestException("是否模板属性不能为空");
        }
        if (ObjectUtil.isNull(multipartFile)) {
            throw new BadRequestException("上传失败");
        }
        //String type = FileUtil.getFileType(suffix);
        String type = isModel ? "MD" : "DO";
        final String filePath = fileProperties.getPath().getPath() + type + File.separator;
        // 保存文件到本地磁盘
        File file = FileUtil.upload(multipartFile, filePath, name);
        if (file == null || !file.isFile()) {
            throw new Exception("文件保存失败");
        }
        return file;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDocument(String name, Boolean isModel, File file, String suffix) throws Exception {
        String docType = !isModel ? DOC_TYPE_UPLOAD : DOC_TYPE_MODEL;
        final String fileType = FileTypeEnum.getType(suffix);
        int docNum = getDocNum(docType);
        final Document document = new Document(name, fileType, file.getAbsolutePath(), docNum, docType);
        if (!isModel) {
            final String fileNameNoEx = FileUtil.getFileNameNoEx(name);
            final String regex = "_";
            if (!fileNameNoEx.contains(regex)) {
                throw new BadRequestException("文件名不符合规则：安全类型不存在");
            }
            final String[] split = fileNameNoEx.split(regex);
            String subName = split[split.length - 1];
            final List<String> safeTypeList = mappingProperties.getSafeType();
            if (StringUtils.isEmpty(subName) || !safeTypeList.contains(subName)) {
                throw new BadRequestException("未知安全类型：" + subName);
            }
            final String safeType = String.valueOf(safeTypeList.indexOf(subName));
            document.setSafeType(safeType);
        }
        final Document save = documentRepository.save(document);
        if (!isModel) {
            parseDocument(fileType, file, save);
        }
    }

    private int getDocNum(String docType) {
        final Document first = documentRepository.findFirstByDocTypeOrderByDocNumDesc(docType);
        int docNum;
        if (first == null) {
            docNum = 1;
        } else {
            docNum = first.getDocNum() + 1;
        }
        return docNum;
    }

    /**
     * 解析非模板文档
     *
     * @param fileType 文件类型 0:word 1:pdf 2:excel
     * @param file     本地磁盘文件
     * @param save     保存数据库的文档信息
     * @throws IOException /
     */
    private void parseDocument(String fileType, File file, Document save) throws IOException {
        // 文档类型为PDF
        if (FileTypeEnum.PDF.getCode().equals(fileType)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // PDF 转 WORD
            PdfDocument pdf = new PdfDocument();
            //Load a PDF file
            pdf.loadFromFile(file.getAbsolutePath(), FileFormat.PDF);
            //Save to .docx file
            pdf.saveToStream(baos, FileFormat.DOCX);

            //Create a PdfTableExtractor instance
            PdfTableExtractor extractor = new PdfTableExtractor(pdf);
            // 表格数据集合
            List<DocumentTableDto> documentTables = new ArrayList<>();
            // 表格位置信息
            int tableIndex = 0;
            //Loop through the pages in the PDF
            for (int pageIndex = 0; pageIndex < pdf.getPages().getCount(); pageIndex++) {
                //Extract tables from the current page into a PdfTable array
                PdfTable[] tableLists = extractor.extractTable(pageIndex);

                //If any tables are found
                if (tableLists != null && tableLists.length > 0) {
                    //Loop through the tables in the array
                    for (PdfTable table : tableLists) {
                        // 表格中文本
                        StringBuilder builder = new StringBuilder();

                        // 行位置信息
                        int rowIndex = 0;
                        // 行数据集合
                        List<DocumentTableRowDto> rows = new ArrayList<>();
                        //Loop through the rows in the current table
                        for (int i = 0; i < table.getRowCount(); i++) {
                            //Loop through the columns in the current table
                            // 当前行数据
                            DocumentTableRowDto row1 = new DocumentTableRowDto();

                            // 列位置信息
                            int cellIndex = 0;
                            // 列数据集合
                            List<DocumentTableCellDto> tCells = new ArrayList<>();
                            for (int j = 0; j < table.getColumnCount(); j++) {
                                //Extract data from the current table cell and append to the StringBuilder
                                String text = table.getText(i, j);
                                builder.append(text + " ");

                                // 处理当前列
                                DocumentTableCellDto cell1 = new DocumentTableCellDto();
                                // 列中段落(只有一个段落)
                                List<DocumentTableParagraphDto> pList = new ArrayList<>();
                                // =========================处理列中段落信息开始===========================
                                // 处理当前列里面的小段落.
                                DocumentTableParagraphDto p = new DocumentTableParagraphDto();
                                p.setStyle("10");
                                p.setLocation(0);
                                p.setText(text);
                                List<DocumentParagraphRunDto> runs = new ArrayList<>();
                                // =========================处理列中段落中文本信息开始===========================
                                DocumentParagraphRunDto run1 = new DocumentParagraphRunDto();
                                run1.setLocation(0);
                                run1.setText(text);
                                runs.add(run1);
                                // =========================处理列中段落中文本信息结束===========================
                                p.setRuns(runs);
                                pList.add(p);
                                // =========================处理列中段落信息结束===========================
                                // 看做列里面只有一个段落
                                cell1.setParagraphs(pList);
                                cell1.setLocation(cellIndex);
                                tCells.add(cell1);
                                cellIndex++;
                            }
                            builder.append("\r\n");

                            row1.setLocation(rowIndex);
                            row1.setCells(tCells);
                            rows.add(row1);
                            rowIndex++;
                        }
                        // 表格数据加入
                        DocumentTableDto t = new DocumentTableDto();
                        t.setDataSize(table.getRowCount());
                        t.setLocation(tableIndex);
                        t.setText(builder.toString());
                        // 列数据
                        t.setRows(rows);
                        documentTables.add(t);
                        tableIndex++;
                    }
                }
            }
            // 1.保存表格信息
            savePdf(save,documentTables);
            // 2.保存段落信息
            pdf.close();
            //try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
            //    parseDocument(save, bais);
            //}
        } else {
            try (InputStream inputStream = new FileInputStream(file)) {
                parseDocument(save, inputStream);
            }
        }
    }

    /**
     * 解析非模板文档
     *
     * @param save        保存数据库的文档信息
     * @param inputStream 文档输入流
     * @throws IOException /
     */
    private void parseDocument(Document save, InputStream inputStream) throws IOException {
        // 读取word文件,转文件流
        DocumentUtils.exportWord(inputStream);
        final List<DocumentParagraph> documentParagraphs = documentParagraphMapper.toEntity(DocumentUtils.getParagraphList());
        documentParagraphs.forEach(documentParagraph -> documentParagraph.setDocument(save));
        documentParagraphRepository.saveAll(documentParagraphs);
        final List<DocumentTable> documentTables = documentTableMapper.toEntity(DocumentUtils.getTableList());
        documentTables.forEach(documentTable -> documentTable.setDocument(save));
        documentTableRepository.saveAll(documentTables);
    }
    /**
     * pdf表格信息
     *
     * @param save     保存数据库的文档信息
     * @param documentTables 表格数据集合
     */
    private void savePdf(Document save, List<DocumentTableDto> documentTables){
        final List<DocumentTable> documentTableList = documentTableMapper.toEntity(documentTables);
        documentTableList.forEach(documentTable -> documentTable.setDocument(save));
        documentTableRepository.saveAll(documentTableList);
    }

    @Override
    public Map<String, Object> queryAll(DocumentQueryCriteria criteria, Pageable pageable) {
        Page<Document> page = documentRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, criteria, cb), pageable);
        return PageUtil.toPage(page.map(documentMapper::toDto));
    }

    @Override
    public List<DocumentDto> queryAll(DocumentQueryCriteria criteria) {
        List<Document> list = documentRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, criteria, cb));
        return documentMapper.toDto(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Document resources) {
        throw new BadRequestException("操作暂不支持");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String docId) {
        final Optional<Document> byId = documentRepository.findById(docId);
        if (!byId.isPresent()) {
            throw new BadRequestException("文档不存在");
        }
        final Document document = byId.get();
        String docType = document.getDocType();
        if (DOC_TYPE_UPLOAD.equals(docType)) {
            // 上传文件 删除解析文档后的段落和表格数据
            documentParagraphRepository.deleteAllByDocument(document);
            documentTableRepository.deleteAllByDocument(document);
        }
        documentRepository.delete(document);
        final Integer docNum = document.getDocNum();
        final List<Document> documentList = documentRepository.findAllByDocTypeAndDocNumGreaterThanOrderByDocNumAsc(docType, docNum);
        if (documentList != null && !documentList.isEmpty()) {
            final Document lastDoc = documentRepository.findFirstByDocTypeAndDocNumLessThanOrderByDocNumDesc(docType, docNum);
            Integer lastDocDocNum = 0;
            if (lastDoc != null) {
                lastDocDocNum = lastDoc.getDocNum();
            }
            for (Document doc : documentList) {
                lastDocDocNum += 1;
                doc.setDocNum(lastDocDocNum);
            }
            documentRepository.saveAll(documentList);
        }
        // 删除本地磁盘对应文件
        FileUtil.del(document.getFilePath());
    }
//
//    @Override
//    public List<Document> getList(DocumentVo vo) {
//        Specification<Document> spec = (root, query, cb) -> {
//            return cb.and(cb.equal(root.get("doc_type").as(String.class), vo.getDocType()));
//        };
//        return documentRepository.findAll(spec);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(String documentTables, String templateName, String head) throws Exception {
        Specification<Document> spec = (root, query, cb) -> {
            return cb.and(cb.equal(root.get("docType").as(String.class), DOC_TYPE_CUSTOM));
        };
        long num = documentRepository.count(spec);
        String[] ids = documentTables.split(",");
        List<String> idList = new ArrayList<>();
        for (String id : ids) {
            if (!StringUtils.isEmpty(id)) {
                idList.add(id);
            }
        }
        List<DocumentTable> datas = documentTableRepository.findAllById(idList);
        String fileName = "自定义报告-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "-" + (num + 1);
        String templatePath = filePath + "/MD";
        String outPath = filePath + "/ZDY";
        String fullFileName = fileName + ".xlsx";
        // 生成word
        if (!templateName.endsWith("xlsx")) {
            fullFileName = fileName + ".docx";
            // 生成文档首页信息
            Map<String, String> paragraphMap = new HashMap<>();
            paragraphMap.put("head", head);
            //paragraphMap.put("fileName", fileName);
            paragraphMap.put("time", LocalDate.now().toString());
            //paragraphMap.put("system", "安全测试自定义测试报告");

            // ------------数据拼装格式begin-----------------
            //familyList.add(new String[]{"露娜", "女", "野友", "666", "6660"});
            //familyList1.add(new String[]{"露娜1", "女", "野友", "666", "6660"});
            //familyList1.add(new String[]{"貂蝉1", "女", "法友", "888", "8880"});
            //familyListMap.put("tl0", familyList);
            //familyListMap.put("tl1", familyList1)
            // ------------数据拼装格式end-----------------;
            // 表格集合
            Map<String, List<String[]>> familyListMap = new HashMap<>();

            for (int i = 0; i < datas.size(); i++) {
                // 表格
                List<String[]> familyList1 = new ArrayList<>();
                DocumentTable table = datas.get(i);
                // 数据库中数据转化
                List<ReadWordCopy.TableRow> tableRows = JSONArray.parseArray(table.getRows(), ReadWordCopy.TableRow.class);
                // 每一行数据
                for (int j = 0; j < tableRows.size(); j++) {
                    // 表格中行
                    List<String[]> familyList = new ArrayList<>();
                    // 行中每一列的数据
                    List<ReadWordCopy.TableCell> cells = tableRows.get(j).getCells();
                    String[] text = new String[cells.size()];
                    for (int k = 0; k < cells.size(); k++) {
                        // 中有段落
                        List<ReadWordCopy.Paragraph> paragraphs = cells.get(k).getParagraphs();
                        // 每一个表格中的文本
                        String paragraphText = "";
                        for (int m = 0; m < paragraphs.size(); m++) {
                            paragraphText = paragraphText + paragraphs.get(m).getText();
                        }
                        text[k] = paragraphText;
                        // 将一行中的每一列的数据填充完整
                    }
                    familyList.add(text);
                    // 将表格中每一列的数据填充到表格里
                    familyList1.addAll(familyList);
                }
                // 将每一个表格填充到map中
                familyListMap.put("tl" + i, familyList1);
            }
            ReadWord.writeDocument(templatePath + "/" + templateName, new String[]{outPath, fullFileName}, paragraphMap, familyListMap);
        } else {
            writeExcel(datas, fullFileName, outPath);
        }
        // 将该文件进行保存
        String docType = DOC_TYPE_CUSTOM;
        int docNum = getDocNum(docType);
        final Document document = new Document(fullFileName, FileTypeEnum.getType(FileUtil.getExtensionName(templateName)), outPath + "/" + fullFileName, docNum, docType);
        documentRepository.save(document);
        return outPath + "/" + fullFileName;
    }

    private void writeExcel(List<DocumentTable> datas, String fullFileName, String outPath) throws Exception {
        ExcelWriter excelWriter = null;
        // 表格数据保存位置修正
        int xx = 0;

        try {
            // 文件位置
            excelWriter = EasyExcel.write(outPath + "/" + fullFileName).build();
            List<List<WriteCellData<String>>> tableDataList = new ArrayList<>();
            for (int i = 0; i < datas.size(); i++) {
                // 表格数据保存位置修正
                Boolean flag = true;

                // 每一个表格
                DocumentTable table = datas.get(i);
                // 表格中所有数据
                List<ReadWordCopy.TableRow> tableRows = JSONArray.parseArray(table.getRows(), ReadWordCopy.TableRow.class);
                // 每一行数据
                for (int j = 0; j < tableRows.size(); j++) {
                    // 每一行中所有列数据
                    List<ReadWordCopy.TableCell> cells = tableRows.get(j).getCells();
                    // 当表格数据列小于等于俩列时,进行行转列
                    if (tableRows.get(0).getCells().size() != 2 && tableRows.get(0).getCells().size() != 1) {
                        System.out.println("无需转换i:" + i);
                        // 表格数据保存位置修正
                        if (flag) {
                            xx = xx + tableRows.size() - (i * 2);
                            flag = false;
                            System.out.println("修正表格数量:" + xx);
                        }
                        List<WriteCellData<String>> tableData = new ArrayList<>();
                        for (int k = 0; k < cells.size(); k++) {
                            // 中有段落
                            List<ReadWordCopy.Paragraph> paragraphs = cells.get(k).getParagraphs();
                            // 每一个表格中的文本
                            String paragraphText = "";
                            for (int m = 0; m < paragraphs.size(); m++) {
                                paragraphText = paragraphText + paragraphs.get(m).getText();
                            }
                            WriteCellData<String> writeCellStyle = new WriteCellData<>(paragraphText);
                            if (j == 0) {
                                writeCellStyle.setType(CellDataTypeEnum.STRING);
                                WriteCellStyle writeCellStyleData = new WriteCellStyle();
                                writeCellStyle.setWriteCellStyle(writeCellStyleData);
                                writeCellStyleData.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                // 背景粉色
                                writeCellStyleData.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                                // 文字颜色
                                RichTextStringData richTextStringData = new RichTextStringData();
                                writeCellStyle.setRichTextStringDataValue(richTextStringData);
                                WriteFont writeFont = new WriteFont();
                                writeFont.setColor(IndexedColors.WHITE1.getIndex());
                                richTextStringData.applyFont(writeFont);
                            }

                            tableData.add(writeCellStyle);
                        }
                        tableDataList.add(tableData);
                    } else {
                        // index 每过俩次加2
                        System.out.println("i:" + i);
                        // 每一列的数据
                        for (int k = 0; k < cells.size(); k++) {
                            // 中有段落
                            List<ReadWordCopy.Paragraph> paragraphs = cells.get(k).getParagraphs();
                            // 每一个表格中的文本
                            String paragraphText = "";
                            for (int m = 0; m < paragraphs.size(); m++) {
                                paragraphText = paragraphText + paragraphs.get(m).getText();
                            }
                            // 第一列数据是表头
                            if (j == 0) {
                                List<WriteCellData<String>> tableData = new ArrayList<>();
                                WriteCellData<String> writeCellStyle = new WriteCellData<>(paragraphText);
                                if (k == 0) {
                                    writeCellStyle.setType(CellDataTypeEnum.STRING);
                                    //writeCellDemoData.setWriteCellStyle(writeCellStyle);
                                    WriteCellStyle writeCellStyleData = new WriteCellStyle();
                                    writeCellStyle.setWriteCellStyle(writeCellStyleData);
                                    // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.
                                    writeCellStyleData.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                    // 背景粉色
                                    writeCellStyleData.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                                    // 文字颜色
                                    RichTextStringData richTextStringData = new RichTextStringData();
                                    writeCellStyle.setRichTextStringDataValue(richTextStringData);
                                    WriteFont writeFont = new WriteFont();
                                    writeFont.setColor(IndexedColors.WHITE.getIndex());
                                    richTextStringData.applyFont(writeFont);
                                }
                                tableData.add(writeCellStyle);
                                tableDataList.add(tableData);
                                // 之后的数据是在相应list中添加
                            } else {
                                WriteCellData<String> writeCellStyle = new WriteCellData<>(paragraphText);
                                if (k == 0) {
                                    writeCellStyle.setType(CellDataTypeEnum.STRING);
                                    //writeCellDemoData.setWriteCellStyle(writeCellStyle);
                                    WriteCellStyle writeCellStyleData = new WriteCellStyle();
                                    writeCellStyle.setWriteCellStyle(writeCellStyleData);
                                    // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.
                                    writeCellStyleData.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                    // 背景粉色
                                    writeCellStyleData.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                                    // 文字颜色
                                    RichTextStringData richTextStringData = new RichTextStringData();
                                    writeCellStyle.setRichTextStringDataValue(richTextStringData);
                                    WriteFont writeFont = new WriteFont();
                                    writeFont.setColor(IndexedColors.WHITE.getIndex());
                                    richTextStringData.applyFont(writeFont);
                                }
                                if ((i * 2) + xx + k == 154) {
                                    System.out.println(i);
                                }
                                System.out.println("最后修正数据:" + ((i * 2) + xx + k));
                                // 表格数据保存位置修正
                               if(tableDataList.size()<=(i * 2 + xx + k)) {
                                   for(int q =0; q<(i * 2 + xx + k);q++) {
                                       List<WriteCellData<String>> tableData = new ArrayList<>();
                                       tableDataList.add(tableData);
                                   }
                                       if((i * 2 + xx + k)>0) {
                                           tableDataList.get(i * 2 + xx + k).add(writeCellStyle);
                                       }

                               } else {
                                   if((i * 2 + xx + k)>0) {
                                       tableDataList.get(i * 2 + xx + k).add(writeCellStyle);
                                   }
                               }
                            }
                        }
                    }
                }
                // 这里放入动态头
                //excelWriter.head(head()).sheet(i).doWrite(data());
            }
            WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
            // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
            excelWriter.write(tableDataList, writeSheet);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    @Override
    public Object uploadTemplate(MultipartFile file) throws Exception {
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));

        System.out.println(filePath + fileName);
        File dest = new File(filePath + "/template/" + fileName);
        if (!dest.exists()) {
            dest.mkdirs();
        }
        try {
            file.transferTo(dest);
            System.out.println("上传成功");
            // 将该文件进行保存
            String docType = DOC_TYPE_CUSTOM;
            int docNum = getDocNum(docType);
            final Document document = new Document(fileName, "2", filePath + "/" + fileName, docNum, docType);
            documentRepository.save(document);
            return new ResponseEntity<>(fileName, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("失敗" + e.getMessage());
            throw new Exception("上传失败，请重新上传");
        }

    }

    @Override
    public List<DocumentTable> getTableList(String documentId) {
        return documentRepository.findById(documentId).map(documentTableRepository::findAllByDocument).orElse(null).stream().filter(c -> c.getDataSize() >= 3).collect(Collectors.toList());
    }
}
